package com.imc.apm.application.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.log.StaticLog;
import com.imc.apm.application.CommonTools;
import com.imc.apm.application.common.ApiRestConstant;
import com.imc.apm.application.service.UCenterRestService;
import com.imc.apm.collect.apmcollect.*;

import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName UCenterRestServiceImpl
 * @Description 对应monitor中cmd的处理接口实现类 入口为lookForApplicationItem
 * @Author Zhang Li Tao
 * @Date 2022/6/1 10:27
 * @Version 1.0
 */
public class UCenterRestServiceImpl implements UCenterRestService {
    /**
     * 用于处理monitor中cmd
     * @param appType 暂时未用到
     * @param unit 暂时未用到
     * @param cmd 暂时未用到
     * @param appId 暂时未用到
     * @return UCenter所需要的返回体对象
     * @throws Exception
     */
    @Override
    public AsnAPMCollectResp lookForApplicationItem(String appType, String unit, String cmd, String appId) throws Exception {
        StaticLog.info("当前处理appType => {}", appType);
        StaticLog.info("当前处理unit => {}", unit);
        StaticLog.info("当前处理cmd => {}", cmd);
        StaticLog.info("当前处理appId => {}", appId);

        /**
         * 这里示例的CMD 需要ip_address  user_name password port
         *
         * $ip_address##$user_name##$password##$port
         * ###localPort##stateName##defaultHost
         * ###getBasicInfo
         * ###table
         */
        // UCenter最终收集所要求的的实体类
        AsnAPMCollectResp asnAPMCollectResp = new AsnAPMCollectResp();

        // 如果cmd里面啥也没有 则直接终止
        if (StrUtil.isEmpty(cmd)) {
            asnAPMCollectResp.result = new AsnAPMCollectErrCode(90402);
            asnAPMCollectResp.message = "cmd为空".getBytes();
            return asnAPMCollectResp;
        }

        /**
         * 处理cmd 取出各部分数据
         */
        List<String> cmdList = StrUtil.split(cmd, "###");
        String basicItem = cmdList.get(0);
        String paramItem = cmdList.get(1);
        String methodName = cmdList.get(2);

        // 验证用户名和密码是否正确 $ip_address##$user_name##$password##$port
        List<String> basicList = StrUtil.split(basicItem, "##");
        String ipAddress = basicList.get(0);
        String userName = basicList.get(1);
        String password = basicList.get(2);
        String port = basicList.get(3);

        if (!StrUtil.equals(userName, "root") || !StrUtil.equals(password, "root")) {
            asnAPMCollectResp.result = new AsnAPMCollectErrCode(90402);
            asnAPMCollectResp.message = "用户名或者密码错误".getBytes();
            return asnAPMCollectResp;
        }

        //  取出所需要的参数
        List<String> paramList = StrUtil.split(paramItem, "##");

        // 拼接GET请求URL
        String currentURL = ipAddress + ":" + port + ApiRestConstant.getURIByMethodName(methodName);
        StaticLog.info("当前请求URL => {}", currentURL);
        String apiResult = "";

        try {
            apiResult = HttpRequest.get(currentURL).execute().body();
        } catch (HttpException e) {
            e.printStackTrace();
            asnAPMCollectResp.result = new AsnAPMCollectErrCode(90402);
            asnAPMCollectResp.message = "请求失败".getBytes();
            return asnAPMCollectResp;
        }

        /**
         * 将请求结果中所需参数取出 并封装成 LinkedList < LinkedList<String> >
         */
        JSONArray jsonArray = new JSONArray(apiResult);
        LinkedList<LinkedList<String>> resultList = new LinkedList();

        for (Object o : jsonArray) {
            JSONObject jsonObject = new JSONObject(o);
            LinkedList<String> currentList = new LinkedList();

            paramList.forEach(param -> currentList.add(jsonObject.get(param).toString()));
            resultList.add(currentList);
        }


        /**
         * 将最终结果处理成 要求的格式
         */
        asnAPMCollectResp.result = new AsnAPMCollectErrCode(90401);
        asnAPMCollectResp.message = "请求成功".getBytes();
        CommonTools.loadResult(asnAPMCollectResp, ArrayUtil.toArray(paramList, String.class), resultList);
        StaticLog.info("最终结果 => {}", asnAPMCollectResp.toString());

        // $ip_address##$user_name##$password##$port###localPort##stateName##defaultHost###getBasicInfo###table

        return asnAPMCollectResp;
    }
}
